<?php

class Serial_topupController extends AdminController {

    public function filters() {
        return array(
            'accessControl',
        );
    }

    public function actionDownload() {

        $rs_serial_topup = Yii::app()->db->createCommand()
                ->select('serial_topup_id, serial_topup_pin,serial_topup_value')
                ->from('sys_serial_topup')
                ->where('UNIX_TIMESTAMP(serial_topup_create_datetime)=:id', array(':id' => $_GET['id']))
                ->order('serial_topup_id ASC')
                ->queryAll();

        $serial_topup_create_datetime = Yii::app()->db->createCommand("SELECT FROM_UNIXTIME('" . $_GET['id'] . "') AS datetime")->queryRow();
        $datetime = function_lib::url_title($serial_topup_create_datetime['datetime']);

        if ($rs_serial_topup) {
            $arr_data[1] = array('Serial Top Up', 'PIN', 'Nominal');
            foreach ($rs_serial_topup as $row_serial_topup) {
                array_push($arr_data, array($row_serial_topup['serial_topup_id'], $row_serial_topup['serial_topup_pin'], $row_serial_topup['serial_topup_value']));
            }

            Yii::import('application.extensions.phpexcel.JPhpExcel');
            $xls = new JPhpExcel('UTF-8', false, 'Data Serial Top Up');
            $xls->addArray($arr_data);
            $xls->generateXML('serial-topup-' . $datetime);
        } else {
            $this->redirect(array('list'));
        }
    }

    public function actionActivate() {
        //print_r($_POST);
        if (isset($_POST['sys_serial_topup'])) {

            $serial_id_start = $_POST['sys_serial_topup']['serial_topup_id_start'];
            $serial_id_end = $_POST['sys_serial_topup']['serial_topup_id_end'];
            $option = $_POST['sys_serial_topup']['option'];
            $option_message = ($option == 1) ? 'activated' : 'deactivated';
            $datetime = ($option == 1) ? date("Y-m-d H:i:s") : null;
            $serial_is_active = ($option == 1) ? 0 : 1;

//            $rs_update = Yii::app()->db->createCommand()->update('sys_serial_topup', array(
//                'serial_topup_active_datetime' => $datetime,
//                'serial_topup_is_active' => $option,
//                    ), "serial_topup_id >= :start AND serial_topup_id <= :end AND serial_topup_is_used = '0' AND serial_topup_is_active = :is_active", array(':start' => $serial_id_start, ':end' => $serial_id_end, ':is_active' => $serial_is_active)
//            );
            $sql_update = "UPDATE sys_serial_topup SET 
                            serial_topup_active_datetime = '$datetime',
                            serial_topup_is_active = '$option'
                            WHERE serial_topup_id >= '$serial_id_start' AND
                            serial_topup_id <= '$serial_id_end' AND 
                            serial_topup_is_used = '0' AND 
                            serial_topup_is_active = '$serial_is_active'
                            ";
            $rs_update = Yii::app()->db->createCommand($sql_update)->Execute();

            if ($rs_update) {
                Yii::app()->user->setFlash('success', 'Serial Top Up has been ' . $option_message . '.');
                $this->redirect(array('list'));
            } else {
                Yii::app()->user->setFlash('error', 'Serial Top Up ' . $option_message . ' failed.');
                $this->redirect(array('activate'));
            }
        }

        $this->render('activate');
    }

    public function actionList() {
        $model = new sys_serial_topup('search');
        $model->unsetAttributes();
        if (isset($_GET['sys_serial_topup']))
            $model->attributes = $_GET['sys_serial_topup'];

        $this->render('list', array(
            'model' => $model,
        ));
    }

    public function actionCreate() {
        $model = new sys_serial_topup;

        if (isset($_POST['sys_serial_topup'])) {
            $last_serial_id = Yii::app()->db->createCommand()
                    ->select('serial_topup_id')
                    ->from('sys_serial_topup')
                    ->where('serial_topup_serial_topup_type_id=:id', array(':id' => $_POST['sys_serial_topup']['serial_topup_serial_topup_type_id']))
                    ->order('serial_topup_id DESC')
                    ->queryScalar();

            //$serial_topup_value = sys_serial_topup_type::model()->findAllByPk($_POST['sys_serial_topup']['serial_topup_serial_topup_type_id'])->serial_topup_type_value;
            $serial_topup_value = Yii::app()->db->createCommand("select serial_topup_type_value from sys_serial_topup_type where serial_topup_type_id = '".$_POST['sys_serial_topup']['serial_topup_serial_topup_type_id']."'")->queryScalar();
            $serial_create_datetime = date("Y-m-d H:i:s");

            $transaction = Yii::app()->db->beginTransaction();
            try {
                for ($i = 1; $i <= $_POST['sys_serial_topup']['serial_topup_count']; $i++) {

                    $rs_insert = Yii::app()->db->createCommand()->insert('sys_serial_topup', array(
                        'serial_topup_id' => ++$last_serial_id,
                        'serial_topup_serial_topup_type_id' => $_POST['sys_serial_topup']['serial_topup_serial_topup_type_id'],
                        'serial_topup_value' => $serial_topup_value,
                        'serial_topup_pin' => $this->generate_pin(6),
                        'serial_topup_create_datetime' => $serial_create_datetime,
                        'serial_topup_is_buyed' => '0',
                        'serial_topup_is_active' => '0',
                        'serial_topup_is_used' => '0',
                            ));
                }
                $id = Yii::app()->db->createCommand("SELECT UNIX_TIMESTAMP('" . $serial_create_datetime . "') AS links_id")->queryRow();
                $transaction->commit();
                Yii::app()->user->setFlash('success', 'Serial successfully generated. Please <a href="' . Yii::app()->baseUrl . '/admin/system/serial_topup/download/' . $id['links_id'] . '">download file excel</a>.');
                $this->redirect(array('list'));
            } catch (CDbException $e) {
                $transaction->rollback();
                Yii::app()->user->setFlash('error', 'Generate serial failed. ');
                $this->redirect(array('create'));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    public function actionView() {
        $id = function_lib::uri_segment(5);
        
        if ($id != '') {
            $model = sys_serial_topup::model()->findByAttributes(array("serial_topup_id" => $id));

            $this->render('view', array(
                'model' => $model,
            ));
        } else {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
    }

    public function loadModel($id) {
        $model = sys_serial_topup::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    private function generate_pin($char_length) {
        $pin = '';
        $pin_str = "1234567809";

        for ($i = 0; $i < strlen($pin_str); $i++) {
            $pin_chars[$i] = $pin_str[$i];
        }

        // randomize the chars
        srand((float) microtime() * 1000000);
        shuffle($pin_chars);

        for ($i = 0; $i < 20; $i++) {
            $char_num = rand(1, count($pin_chars));
            $pin .= $pin_chars[$char_num - 1];
        }
        $pin = substr($pin, 0, $char_length);

        return $pin;
    }

}